<?php


namespace app\admin\system\controller;


use app\admin\system\logic\AdminLogic;
use app\admin\system\logic\RoleLogic;
use app\common\controller\BaseAdminController;
use app\model\SysAdmin;
use app\model\SysRoleMenu;
use think\facade\Db;

class RoleController extends BaseAdminController
{
    protected $noNeedRight = [
        'listNormalRole',
        'listRoleElSelect',
    ];
    protected $idKey = 'roleId';

    protected function init()
    {
        parent::init();
        $this->logic = new RoleLogic();
    }

    protected function searchWhere()
    {
        $where = [];
        $this->form['roleName'] && $where[] = ['roleName', 'like', "%{$this->form['roleName']}%"];
        $this->form['roleCode'] && $where[] = ['roleCode', 'like', "%{$this->form['roleCode']}%"];
        $this->form['roleStatus'] && $where[] = ['roleStatus', '=', $this->form['roleStatus']];
        return $where;
    }

    public function listRoleElSelect()
    {
        $data = $this->logic->getList([
            ['status', '=', 1]
        ], [
            'name as label',
            'id as value',
        ]);
        return $this->success($data);
    }

    public function allocationMenu()
    {
        $menuIds = input('menuIds');
        $roleId = input('roleId');
        $inst = [];
        foreach ($menuIds as $id) {
            $inst[] = [
                'role_id' => $roleId,
                'menu_id' => $id,
            ];
        }
        Db::transaction(function () use ($roleId, $inst) {
            SysRoleMenu::where('role_id', '=', $roleId)->delete();
            SysRoleMenu::insertAll($inst);
        });
        return $this->success();
    }

    public function listNormalRole()
    {
        $id = input('id');

        $role_str = SysAdmin::where([
            'id' => $id
        ])->value("role_ids");
        $role_ids = [];
        if ($role_str) {
            $role_ids = explode(',', $role_str);
            $role_ids = array_map(function ($v) {
                return intval($v);
            }, $role_ids);
        }
        $data = $this->logic->getList([
            ['roleStatus', '=', 0]
        ], [
            'roleName as label',
            'roleId as value'
        ]);
        return $this->success([
            'data1' => $data, //左边的未选择数据
            'data2' => $role_ids, //右边的已选择数据
        ]);
    }

    public function assignUserRole()
    {
        $id = input('id');
        $roleIds = input('roleIds');
        $logic = new AdminLogic();
        $logic->update([
            "role_ids" => implode(',', $roleIds)
        ], [
            'id' => $id
        ]);
        return $this->success();
    }

    public function read()
    {
        $model = $this->logic->find(request()->input('id'));
        if ($model) {
            return $this->success($model->toArray());
        } else {
            return $this->error('未查找到信息');
        }
    }
}